<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Category class
 *
 * @category	Admin
 */
class CategoryAction extends AdminAction
{

	protected $Category;
    protected $Moderator;

	function _initialize()
	{
		parent::_initialize();
		$this->Category = D('Category');
		$this->Moderator = D('Moderator');
	}


	//分类列表
	function manage()
	{
		if ($this->isPost())
		{

			$cateOrder       = $_POST['cateOrder'];
			$cateName        = $_POST['cateName'];
			$cateStatus      = $_POST['cateStatus'];
			$newTopCateName  = $_POST['newTopCateName'];
			$newTopCateOrder = $_POST['newTopCateOrder'];
			$newCateName	 = $_POST['newCateName'];
			$newCateOrder    = $_POST['newCateOrder'];

			/*---------------- 更新已有分类数据 -----------------*/
			if (!empty($cateName))
			{
				foreach ($cateName as $key => $value)
				{
					if (!empty($cateName[$key]))
					{
						$data = array(
							'name'   => trim($cateName[$key]),
							'status' => intval($cateStatus[$key]),
							'display_order' => intval($cateOrder[$key]),
						);
						$where = array('category_id' => $key);
						$this->Category->where($where)->save($data);
					}
				}
			}

			/*----------------- 新增一级分类 -------------------*/
			if (!empty($newTopCateName))
			{
				foreach ($newTopCateName as $key => $value)
				{
					if (!empty($newTopCateName[$key]))
					{
						$data = array(
							'name'   => trim($newTopCateName[$key]),
							'status' => 1,
							'level'  => 1,
							'parent' => 0,
							'display_order' => intval($newTopCateOrder[$key]),
						);
						$lastID = $this->Category->add($data);
						$where = array('category_id' => $lastID);
						$this->Category->where($where)->setField('path', $lastID);
					}
				}
			}

			/*--------------- 新增二三级分类 -----------------*/
			if (!empty($newCateName))
			{
				foreach ($newCateName as $idx => $tmp)
				{
					$parent = $this->Category->find($idx);

					/*--------------------- 分类版主相关 -----------------------*/
					$pCategoryIDs = get_parent_category_ids($idx);
					$modCategoryIDs = ($pCategoryIDs ? $pCategoryIDs : array());
					array_push($modCategoryIDs, $idx);
					$where['category_id'] = array('in', $modCategoryIDs);
					$moderatorUsers = $this->Moderator->where($where)->group('user_id')->select();
					foreach ($tmp as $key => $value)
					{
						if (!empty($newCateName[$idx][$key]))
						{
							$data = array(
								'name'   => trim($newCateName[$idx][$key]),
								'parent' => intval($parent['category_id']),
								'status' => 1,
								'display_order'  => intval($newCateOrder[$idx][$key]),
							);
							$lastID = $this->Category->add($data);

							$data = array(
								'path'  => $parent['path'].','.$lastID,
								'level' => $parent['level'] + 1,
							);
							$where = array('category_id' => $lastID);
							$this->Category->where($where)->save($data);

							/*-------------- 版主设置(上级分类有版主时继承到子分类) ---------------*/
							if (!empty($moderatorUsers))
							{
								foreach ($moderatorUsers as $value)
								{
									$data = array(
										'user_id'      => intval($value['user_id']),
										'category_id'  => intval($lastID),
										'username'     => trim($value['username']),
										'is_inherited' => 1,
									);
									$this->Moderator->replace($data);
								}
							}
						}
					}
				}
			}

			$this->Category->cacheCategories();
			$this->success(L('category_updated_succeed'));
		}
		else
		{
			$categoryList = $this->Category->getCategoryList();
			$moderators = F('cache_moderators');
			if (!empty($categoryList))
			{
			    foreach ($categoryList as $key => $value)
			    {
                    $categoryList[$key]['moderators'] = isset($moderators[$value['category_id']]) ? $moderators[$value['category_id']] : array();
			    }
			}

			$this->assign('categoryList', $categoryList);
			$this->display();
		}
	}


    // 创建分类
	function add()
	{
		$this->edit();
	}


	// 修改分类
	function edit()
	{
		$categoryID = isset($_GET['category_id']) ? intval($_GET['category_id']) : 0;
		$result = $this->Category->find($categoryID);
		$this->assign('rs', $result);

		$cateStatus = array(1 => L('yes'), 0 => L('no'));
		$cateStatusChecked = $categoryID ? $result['status'] : 1;
		$this->assign('cateStatus', $cateStatus);
		$this->assign('cateStatusChecked', $cateStatusChecked);

		$level = $categoryID ? 3 : 2;
		$pCateOptions = $this->Category->getParentCategoryOptions($categoryID, $level);
		$this->assign('pCateOptions', $pCateOptions);

		if ($categoryID && empty($result))
		{
			$this->error(L('category_does_not_exist'));
		}
		$this->display('edit');
	}


	// 保存分类数据
	function save()
	{
		$categoryID = intval($_POST['category_id']);
		$parent = intval($_POST['parent']);
		$parent = $this->Category->find($parent);

		$data = array(
			'name'           => $_POST['name'],
			'keywords'       => $_POST['keywords'],
			'description'    => $_POST['description'],
			'parent'         => $_POST['parent'],
			'level'          => $parent ? $parent['level'] + 1 : 1,
			'status'         => $_POST['status'],
			'redirect'       => $_POST['redirect'],
			'image'          => $_POST['image'],
			'display_order'  => intval($_POST['display_order']),
		);

		if (false == $this->Category->create())
		{
			$this->error($this->Category->getError());
		}

		if ($categoryID)
		{
			$category = $this->Category->find($categoryID);
			/*---------------- 改变所属上级 -----------------*/
			if (($category['parent'] != $parent))
			{
				$subCategory = $this->Category->where('parent='.$categoryID)->find();
				if ($subCategory)
				{
					$this->error(L('has_sub_category'));
				}
				$data['path'] = $parent['path']. ',' .$categoryID;
			}
			$this->Category->where('category_id='.$categoryID)->save($data);
		}
		else
		{
			$lastID = $this->Category->add($data);
			$catePath = $parent ? $parent['path'] .','. $lastID : $lastID;
			$this->Category->where('category_id='.$lastID)->setField('path', $catePath);
		}

		$this->Category->cacheCategories();

		$this->assign('jumpUrl', __URL__.'/manage');
		$message = $categoryID ? L('category_edited_succeed') : L('category_created_succeed');
		$this->success($message);
	}


	//合并分类
	function merge()
	{
		if ($this->isPost())
		{
			$source = intval($_POST['source']);
			$target = intval($_POST['target']);

			if (!$source || !$target)
			{
				$this->error(L('category_not_specified'));
			}
			if ($source == $target)
			{
				$this->error(L('category_source_eq_target'));
			}

			//检查是否有子分类
			$this->Category->where('parent='.$source)->find();
			if (!empty($subCategory))
			{
				$this->error(L('category_source_has_sub'));
			}

			//改变问题所属分类
			$Question = D('Question');
			$Question->where('category_id='.$source)->setField('category_id', $target);

			//改变答案所属分类
			$Answer = D('Answer');
			$Answer->where('category_id='.$source)->setField('category_id', $target);

			 //改变评论所属分类
			$Comment = D('Comment');
			$Comment->where('category_id='.$source)->setField('category_id', $target);

			//删除源分类
			$this->Category->delete($source);

			$this->Category->cacheCategories();

			$this->assign('jumpUrl', __URL__.'/manage');
			$this->success(L('category_merged_succeed'));
		}
		else
		{
			$pCategoryOptions = $this->Category->getParentCategoryOptions(0);
			$this->assign('pCategoryOptions', $pCategoryOptions);
			$this->display();
		}
	}


	//删除分类
	function delete()
	{
	    $this->assign('jumpUrl', __URL__.'/manage');

	    $categoryID  = intval($_REQUEST['category_id']);
		$map = array('parent' => $categoryID);
		$subCategory = $this->Category->where($map)->find();

		if (!empty($subCategory))
		{
			$this->error(L('has_sub_category'));
		}

		if (isset($_POST['action']['confirm']))
		{
            $this->Category->deleteCategory($categoryID);
    		$this->Category->cacheCategories();
    		$this->success(L('category_deleted_succeed'));
		}
		elseif (isset($_POST['action']['cancel']))
		{
			$this->redirect('Admin-Category/manage');
		}

		$this->assign('action', __ACTION__.'/category_id/'.$categoryID);
		$this->confirm(L('category_deleted_confirm'));
	}


	//分类版主
	function moderator()
	{
		$categoryID = intval($_REQUEST['category_id']);
		$category = $this->Category->find($categoryID);
		$subCategoryIDs = get_sub_category_ids($categoryID);

		if (empty($category))
		{
			$this->assign('jumpUrl', __URL__.'/manage');
			$this->error(L('category_does_not_exist'));
		}

		if ($this->isPost())
		{
			//新增分类版主
			$inherited       = intval($_POST['inherited']);
			$newModerator    = trim($_POST['newModerator']);
			$newDisplayOrder = intval($_POST['newDisplayOrder']);
			if ($newModerator)
			{
				$userInfo = $this->_User->getUserByName($newModerator);
				if (!$userInfo)
				{
					$this->error(L('user_does_not_exist'));
				}
				else
				{
					$data = array(
						'user_id'       => $userInfo['user_id'],
						'category_id'   => $categoryID,
						'username'      => $userInfo['username'],
						'is_inherited'  => 0,
						'display_order' => $newDisplayOrder,
					);
					$this->Moderator->replace($data);
					//改变管理分组为版主
					$where = array('user_id' => $userInfo['user_id']);
					if (!in_array($userInfo['admin_group'], array(1,2)))
					{
						$userData['admin_group'] = 3;
						$userData['user_group'] = 3;
					}
					$this->_User->where($where)->save($userData);
					//继承到子分类
					if ($category['level'] <= 2 && $inherited)
					{
						foreach ($subCategoryIDs as $value)
						{
							$data['category_id'] = $value;
							$data['is_inherited'] = 1;
							$this->Moderator->replace($data);
						}
					}
				}
			}

			//编辑已有版主
			$delete = $_POST['delete'];
			$displayOrder = $_POST['displayOrder'];
			if (is_array($displayOrder))
			{
				foreach ($displayOrder as $key => $value)
				{
					$data = array('display_order' => intval($value));
					$where = array('category_id' => $categoryID, 'user_id' => $key);
					$this->Moderator->where($where)->save($data);
				}
			}

			//删除已有管理人员
			$subCategoryIDs = implode(",", $subCategoryIDs);
			$subCategoryIDs = $subCategoryIDs ? $subCategoryIDs : 0;
			if (!empty($delete))
			{
				foreach ($delete as $key => $value)
				{
					$where = " user_id='$key' AND ((category_id='$categoryID' AND is_inherited=0) OR (category_id IN ($subCategoryIDs) AND is_inherited=1))";
					$this->Moderator->where($where)->delete();
				}
			}

			$this->Moderator->cacheModerators();
			$this->success(L('moderator_updated_succeed'));
		}
		else
		{
		    $where = array('category_id' => $categoryID);
			$moderatorList = $this->Moderator->where($where)->select();
			$this->assign('category', $category);
			$this->assign('moderatorList', $moderatorList);
			$this->display();
		}
	}


	//同步分类
	function synchronise()
	{
	    $Question = D('Question');

	    //重置问题计数
	    $this->Category->setField('question_count', 0);

	    $order = array('level' => 'desc');
	    $categories = $this->Category->order($order)->select();
        if (!empty($categories))
        {
        	foreach ($categories as $value)
    	    {
    	        //当前分类问题计数
    	        $map = array('category_id' => $value['category_id'], 'is_visible' => 1);
            	$count = $Question->where($map)->count();

            	//非终极分类把直系子分类问题数相加
    	        if (!is_ultimate_category($value['category_id']))
    	        {
    	            $subCategoryIDs = get_sub_category_ids($value['category_id'], 1, 1);
    	            $map = array('category_id' => array('in', $subCategoryIDs));
    	            $subCategories = $this->Category->where($map)->select();
    	            foreach ($subCategories as $sub)
    	            {
    	               $count += $sub['question_count'];
    	            }
    	        }
    	        $where = array('category_id' => $value['category_id']);
            	$this->Category->where($where)->setField('question_count', $count);
    	    }
        }
	}

}
//End Class

/* End of file CategoryAction.class.php */
/* Location: App/Lib/Action/Admin/CategoryAction.class.php */